package com.docmgmt.mvp.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.docmgmt.mvp.entity.FileEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 文件Mapper
 *
 * @author Dora
 */
@Mapper
public interface FileMapper extends BaseMapper<FileEntity> {

    /**
     * 查询用户可见的文件（基于privacy_level和user_id）
     *
     * @param userId 用户ID
     * @param deptId 部门ID
     * @return 可见文件列表
     */
    @Select("SELECT * FROM doc_file WHERE " +
            "(creator_id = #{userId}) OR " +
            "(privacy_level IN ('shared', 'public')) OR " +
            "(privacy_level = 'shared' AND creator_id IN " +
            "  (SELECT id FROM sys_user WHERE dept_id = #{deptId}))")
    List<FileEntity> selectVisibleFiles(@Param("userId") Long userId, @Param("deptId") Long deptId);

    /**
     * 根据MD5查询文件（去重）
     */
    @Select("SELECT * FROM doc_file WHERE md5 = #{md5Hash} AND is_deleted = 0 LIMIT 1")
    FileEntity selectByMd5(@Param("md5Hash") String md5Hash);

    /**
     * 统计用户存储使用量
     */
    @Select("SELECT COALESCE(SUM(size), 0) FROM doc_file WHERE creator_id = #{userId} AND is_deleted = 0")
    Long selectStorageUsedByUser(@Param("userId") Long userId);

    /**
     * 查询用户可访问的文档（全局范围）- 用于 AI 问答权限控制
     *
     * @param userId 用户ID
     * @param deptId 部门ID
     * @return 可访问的文件列表
     */
    @Select("SELECT * FROM doc_file WHERE " +
            "ragflow_doc_id IS NOT NULL AND " +
            "is_deleted = 0 AND " +
            "(" +
            "  privacy_level = 'public' OR " +
            "  (privacy_level = 'shared' AND creator_dept_id = #{deptId}) OR " +
            "  (privacy_level = 'privacy' AND creator_id = #{userId})" +
            ")")
    List<FileEntity> selectAccessibleDocsForGlobal(@Param("userId") Long userId, @Param("deptId") Long deptId);

    /**
     * 根据文件名搜索文件（模糊匹配）
     *
     * @param keyword 搜索关键词
     * @param userId  用户ID（用于权限过滤）
     * @return 匹配的文件列表
     */
    @Select("SELECT * FROM doc_file WHERE name LIKE CONCAT('%', #{keyword}, '%') " +
            "AND is_deleted = 0 " +
            "ORDER BY created_at DESC")
    List<FileEntity> searchByName(@Param("keyword") String keyword, @Param("userId") Long userId);

    /**
     * 查询用户上传的文件列表（支持文件夹过滤和排序）
     *
     * @param userId    用户ID
     * @param folderId  文件夹ID（可为null）
     * @param sortBy    排序字段
     * @param sortOrder 排序方向（asc/desc）
     * @return 文件列表
     */
    @Select("<script>" +
            "SELECT * FROM doc_file WHERE creator_id = #{userId} AND is_deleted = 0 " +
            "<if test='folderId != null'> AND folder_id = #{folderId}</if> " +
            "ORDER BY ${sortBy} ${sortOrder}" +
            "</script>")
    List<FileEntity> listFilesByCreator(@Param("userId") Long userId,
                                        @Param("folderId") Long folderId,
                                        @Param("sortBy") String sortBy,
                                        @Param("sortOrder") String sortOrder);
}
